package tk.xboot.boot.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Aspect
@Order(1)
@Component
public class WebLogAspect {

    final ThreadLocal<Map<String, Object>> localProperties = new ThreadLocal<Map<String, Object>>() {
        public Map<String, Object> initialValue() {
            return new LinkedHashMap<>();
        }
    };

    //ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Pointcut("execution(public * tk.xboot.boot.controller..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        localProperties.get().put("start", System.nanoTime());

        // RequestContextUtils.getLocaleResolver();
        // ServletRequestAttribute
        // GET more details https://blog.csdn.net/suddev/article/details/79464574
        // or visit : https://blog.csdn.net/u012706811/article/details/53432032
        /*ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        //从session里面获取对应的值
        String myValue = (String) requestAttributes.getAttribute("my_value", RequestAttributes.SCOPE_SESSION);*/

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();
        Signature s = joinPoint.getSignature();
        // log the message of the request.
        log.info("Request::  url:{},    method:{},   IP:{}, classMethod:{}.{}  params{}",
                req.getRequestURL(),req.getMethod(),req.getRemoteHost(),
                s.getDeclaringTypeName(),s.getName(),
                Arrays.toString(joinPoint.getArgs()));
    }



    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("Response:{}",ret);
        log.info("Spend time:{}",System.currentTimeMillis() - 0);
    }
}
